<template>
  <d2-container>
    <template slot="header">
      <el-form
        class="header-area"
        ref="indexForm"
        :model="indexForm"
        label-width="120px"
        style="height: auto"
      >
        <el-row>
          <el-col :span="4">
            <el-form-item label="采购订单编码" prop="orderNo">
              <el-input type="text" v-model="indexForm.orderNo" placeholder="采购订单编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="付款状态" prop="payStatus">
              <el-select v-model="indexForm.payStatus" placeholder="全部" style="width: 100%;">
                <el-option label="全部" value></el-option>
                <el-option label="未付" value="0"></el-option>
                <el-option label="部分付款" value="1"></el-option>
                <el-option label="已付款" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="供应商名称" prop="supplierName">
              <el-input type="text" v-model="indexForm.supplierName" placeholder="供应商名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="采购原因" prop="purchaseReason">
              <el-input type="text" v-model="indexForm.purchaseReason" placeholder="采购原因"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="4">
            <el-form-item label="审核状态" prop="status">
              <el-select v-model="indexForm.status" placeholder="全部" style="width: 100%;">
                <el-option label="全部" value></el-option>
                <el-option label="未提交" value="0"></el-option>
                <el-option label="审核中" value="1"></el-option>
                <el-option label="审核通过" value="2"></el-option>
                <el-option label="审核拒绝" value="3"></el-option>
                <el-option label="采购取消" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="入库状态" prop="stockStatus">
              <el-select v-model="indexForm.stockStatus" placeholder="全部" style="width: 100%;">
                <el-option label="全部" value></el-option>
                <el-option label="未入库" value="1"></el-option>
                <el-option label="部分入库" value="2"></el-option>
                <el-option label="全部入库" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="4">
            <el-form-item label="时间类型" prop="timeType">
              <el-select v-model="indexForm.timeType" placeholder="全部" style="width: 100%;">
                <el-option label="请选择" value></el-option>
                <el-option label="创建时间" value="0"></el-option>
                <el-option label="审核时间" value="1"></el-option>
                <el-option label="计划到货日期" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="时间范围" prop="time">
              <el-date-picker
                v-model="time"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="timestamp"
                align="right"
                :default-time="['00:00:00', '23:59:59']"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div class="search-submit">
              <el-button type="primary" size="medium" @click="submitForm('indexForm')">查询</el-button>
              <el-button type="primary" plain size="medium" @click="resetForm('indexForm')">重置</el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
    </template>

    <!-- 主体部分 -->
    <template>
      <!-- 表格上方的按钮 -->
      <div class="table-header">
        <el-button type="primary" @click="addPurchase()">新建采购</el-button>
      </div>

      <!-- 表格 -->
      <!-- 表格统一用 带边框、条纹间隔 的样式 -->

      <el-table
        :data="tableData"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column type="index" fixed label="序号" width="50"></el-table-column>
        <el-table-column prop="orderNo" label="采购订单编码" width="220"></el-table-column>
        <el-table-column prop="purchaseReason" label="采购原因简述" width="200"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" width="110"></el-table-column>
        <el-table-column prop="supplierContact" label="联系人" width="100"></el-table-column>
        <el-table-column prop="expectedArrivalTime" label="计划到货日期" width="110" :formatter="forDate"></el-table-column>
        <el-table-column prop="paidAmount" label="已付金额(元)" width="110"></el-table-column>
        <el-table-column prop="toPayAmount" label="未付金额(元)" width="110"></el-table-column>
        <el-table-column prop="amountTotal" label="总金额(元)" width="110"></el-table-column>
        <el-table-column prop="statusDesc" label="审核状态" width="80"></el-table-column>
        <el-table-column prop="authTime" label="审核时间" width="160" :formatter="forDateCreateTime"></el-table-column>
        <el-table-column prop="payStatusDesc" label="付款状态" width="80"></el-table-column>
        <el-table-column prop="stockStatusDesc" label="入库状态" width="80"></el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="150" :formatter="forDateCreateTime"></el-table-column>

        <el-table-column label="操作" fixed="right" width="280">
          <template slot-scope="scope">
            <el-button type="primary" size="small"
              @click.native.prevent="detailRow(scope.row.id)" >查看</el-button>
            <el-button v-if="checkSubmitAndDeleteBtn(scope.row.status)" type="primary" plain size="small"
              @click.native.prevent="updateRow(scope.row.id, scope.row.status)" >编辑</el-button>
            <el-button v-if="checkSubmitAndDeleteBtn(scope.row.status)" type="warning" plain size="small"
              @click.native.prevent="deleteRow(scope.row, scope.row.status)" >删除</el-button>
            <el-button v-if="checkSubmitAndDeleteBtn(scope.row.status)" type="primary" plain size="small"
              @click.native.prevent="submitRow(scope.row, scope.row.status)" >提交</el-button>
            <el-button v-if="checkToAuditBtn(scope.row.status)" type="primary" plain size="small"
              @click.native.prevent="toAudit(scope.row, scope.row.status)" >审核</el-button>
            <el-button v-if="checkAuditedBtn(scope.row.status, scope.row.stockStatus)" type="success" plain size="small"
              @click.native.prevent="toStock(scope.row)" >去入库</el-button>
            <el-button v-if="checkCancelBtn(scope.row.status, scope.row.stockStatus)" type="danger" plain size="small"
              @click.native.prevent="cancelRow(scope.row, scope.row.status)" >取消采购</el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>

    <template slot="footer">
      <div class="page">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
        ></el-pagination>
      </div>
    </template>

    <!-- 详情页 -->
    <template>
      <div>
        <keep-alive>
          <detailPage
            :detailPage="detailComponent"
            @on-detailPage-change="onDetailPageChange"
            @on-loadlist-change="fetchData"
            :dOrderId="orderId"
            @on-id-change="onIdChange"
          ></detailPage>
        </keep-alive>
      </div>
    </template>
  </d2-container>
</template>

<script>
import {
  getOrderPage, submitOrder, delOrder, auditOrder, cancelOrder
} from '@api/purchase/purchase'
import detailPage from './detail'
import dayjs from 'dayjs'

export default {
  name: 'purchase-index',
  components: {
    detailPage
  },
  data () {
    return {
      indexForm: {
        orderNo: '',
        purchaseReason: '',
        supplierName: '',
        status: '',
        payStatus: '',
        stockStatus: '',
        timeType: '',
        startTime: '',
        endTime: ''
      },
      loading: false,
      time: [],
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      multipleSelection: [],
      detailComponent: false,
      orderId: '',

      // 去入库表单
      toStockForm: {
        id: '',
        supplierId: '',
        supplierCode: '',
        supplierName: '',
        orderNo: ''
      }
    }
  },

  mounted () {
    this.fetchData()
  },
  methods: {
    fetchData () {
      this.loading = true

      if (this.indexForm.timeType == '' && this.time[0] != null) {
        this.$message({ message: '请选择时间类型', type: 'warning' })
        return
      }
      if (this.indexForm.timeType != '' && this.time[0] == null) {
        this.$message({ message: '请选择时间范围', type: 'warning' })
        return
      }

      this.indexForm.startTime = this.time[0] == null ? '' : dayjs(this.time[0]).format('YYYY-MM-DD HH:mm:ss')
      this.indexForm.endTime = this.time[1] == null ? '' : dayjs(this.time[1]).format('YYYY-MM-DD HH:mm:ss')
      getOrderPage({
        orderNo: this.indexForm.orderNo,
        purchaseReason: this.indexForm.purchaseReason,
        supplierName: this.indexForm.supplierName,
        status: this.indexForm.status,
        payStatus: this.indexForm.payStatus,
        stockStatus: this.indexForm.stockStatus,
        timeType: this.indexForm.timeType,
        startTime: this.indexForm.startTime,
        endTime: this.indexForm.endTime,

        currentPage: this.currentPage,
        pageSize: this.pageSize
      })
        .then(res => {
          this.tableData = res.data.content
          this.total = res.data.total
          this.loading = false
        })
        .catch(err => {
          console.log('err', err)
          this.loading = false
        })
    },
    toStock (row) {
      if (row.status != 2 || row.stockStatus == 3) {
        this.$message({ message: '状态不是已审核且未入库完成，不允许入库', type: 'error' })
        return
      }

      this.toStockForm.id = row.id
      this.toStockForm.orderNo = row.orderNo
      this.toStockForm.supplierId = row.supplierId
      this.toStockForm.supplierCode = row.supplierCode
      this.toStockForm.supplierName = row.supplierName

      sessionStorage.setItem('toStockInOrderAddFlag', 'fromPurchaseOrder')
      sessionStorage.setItem('stockInOrder_add_purchaseOrder', JSON.stringify(this.toStockForm))

      // console.log('stockInOrder_add_purchaseOrder', this.toStockForm);
      console.log('stockInOrder_add_purchaseOrder', JSON.stringify(this.toStockForm))
      // console.log('stockInOrder_add_purchaseOrder', JSON.parse(this.toStockForm));

      this.$router.push({
        path: '/stockIn/purchaseStockInAdd'
      })
    },

    handleSizeChange (val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange (val) {
      this.currentPage = val
      this.fetchData()
    },
    forDate (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.expectedArrivalTime).format('YYYY-MM-DD')
    },
    forDateCreateTime (row, column) {
      return row.createTime == null
        ? ''
        : dayjs(row.createTime).format('YYYY-MM-DD HH:mm:ss')
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    resetPage () {
      this.currentPage = 1
      this.pageSize = 10
      this.total = 0
    },
    submitForm (formName) {
      this.resetPage()
      this.fetchData()
    },
    resetForm (formName) {
      this.$refs[formName].resetFields()
      this.time = []
      this.resetPage()
      this.fetchData()
    },
    // 新增
    addPurchase () {
      this.$router.push({
        path: '/purchase/add'
      })
    },
    // 编辑
    updateRow (id, status) {
      sessionStorage.setItem('purchaseOrderId', id)
      this.$router.push('/purchase/update')
    },
    toAudit (row, status) {
      if (status == 1) {
        sessionStorage.setItem('purchaseOrderId', row.id)
        this.$router.push('/purchase/audit')
      } else {
        this.$message({ message: '状态不是待审核，请刷新后重试', type: 'warning' })
      }
    },
    detailRow (id) {
      this.detailChange()
      this.idChange(id)
    },
    /** 双向绑定 start */
    detailChange () {
      this.detailComponent = !this.detailComponent
    },
    onDetailPageChange (val) {
      this.detailComponent = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },
    idChange (val) {
      this.orderId = val
    },
    onIdChange (val) {
      this.orderId = val // ④外层调用组件方注册变更方法，将组件内的数据变更，同步到组件外的数据状态中
    },

    checkSubmitAndDeleteBtn (status) {
      if (status == 0 || status == 3) {
        return true
      }
    },
    checkToAuditBtn (status) {
      if (status == 1) {
        return true
      }
    },
    checkAuditedBtn (status, stockStatus) {
      if (status == 2 && stockStatus != 3) { // 已审核未全部入库
        return true
      }
    },
    checkCancelBtn (status, stockStatus) {
      if (status == 2 && stockStatus == 1) { // 已审核未入库
        return true
      }
    },
    submitRow (row, status) {
      this.$confirm('确认' + '提交' + ('【' + row.orderNo + '】？')).then(_ => {
        this.loading = true
        submitOrder({
          orderId: row.id
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },

    cancelRow (row, status) {
      this.$confirm('确认' + '取消' + ('【' + row.orderNo + '】？')).then(_ => {
        this.loading = true
        cancelOrder({
          orderId: row.id
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },

    deleteRow (row, status) {
      this.$confirm('确认' + '删除' + ('【' + row.orderNo + '】？')).then(_ => {
        this.loading = true
        delOrder({
          orderId: row.id
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    },

    /** 双向绑定 end */
    // 操作用户状态
    operateUserStatus (row, status) {
      this.$confirm(
        '确认' +
          (status == 0 ? '激活' : '冻结') +
          ('【' + row.userName + '】？')
      ).then(_ => {
        this.loading = true
        operateUserStatus({
          id: row.id,
          status: status
        })
          .then(res => {
            if (res.code == '000000') {
              this.$message({ message: res.message, type: 'success' })
              this.fetchData()
              this.loading = false
            } else {
              this.$message({ message: res.message, type: 'error' })
            }
          })
          .catch(err => {
            console.log('err', err)
            this.loading = false
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.header-area {
  .el-row {
    .el-col {
      .el-form-item {
        margin-bottom: 20px;
      }
    }
    &:last-child {
      .el-col {
        .el-form-item {
          margin-bottom: 0;
        }
      }
    }
  }
}
</style>
